package beans;

import dao.CommentDAO;
import dao.UserDAO;
import model.Comment;
import utils.GetBeanUtil;
import utils.UpdateUtil;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import java.util.ArrayList;
import java.util.List;

@ManagedBean
@ViewScoped
public class CommentBean {
    private Comment comment;
    private List<Comment> comments;

    public CommentBean() {
        comment = new Comment();
        comments = new ArrayList<Comment>();
    }

    public List<Comment> getComments() {
        CommentDAO commentDAO = new CommentDAO();
        DocumentsBean documentsBean = (DocumentsBean) GetBeanUtil.getBean("documentsBean");
        comments = commentDAO.getCommentsByDocumentId(documentsBean.getDocument().getIdDocument());
        UserDAO userDAO = new UserDAO();
        for(int i = 0; i < comments.size(); i++) {
            comments.get(i).setUser(userDAO.getUserById(comments.get(i).getUser().getIdUser()));
        }
        return comments;
    }

    public void setComments(List<Comment> comments) {
        this.comments = comments;
    }

    public Comment getComment() {
        return comment;
    }

    public void setComment(Comment comment) {
        this.comment = comment;
    }

    public void sendComment() {
        try {
            CommentDAO commentDAO = new CommentDAO();
            UserBean userBean = (UserBean) GetBeanUtil.getBean("userBean");
            DocumentsBean documentsBean = (DocumentsBean) GetBeanUtil.getBean("documentsBean");
            comment.setUser(userBean.getUser());
            comment.setDocument(documentsBean.getDocument());
            commentDAO.insertComment(comment);
            UpdateUtil.updatePage();
        }
        catch (Exception e) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", e.toString()));
        }
    }

    public void deleteComment() {
        try {
            CommentDAO commentDAO = new CommentDAO();
            commentDAO.deleteCommentById(comment.getIdComment());
            UpdateUtil.updatePage();
        }
        catch (Exception e) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", e.toString()));
        }
    }






}
